import React, { PureComponent } from 'react';
import { FormattedMessage } from 'umi';
import { Spin, Tag, Menu, Avatar, Badge, Tooltip } from 'antd';
import moment from 'moment';
import groupBy from 'lodash/groupBy';
import LinkTo from '@/components/LinkTo';
import { connect } from 'umi';
// import cookie from 'js-cookie';
// import { history } from 'umi';
// import NoticeIcon from '../NoticeIcon';
// import HeaderSearch from '../HeaderSearch';
import { IconUser, IconPassword, IconFeedback, IconFeedbackList } from '@/components/Custom/Icons';
import { FeedbackModal } from '@/pages/Feedback';
import { eventTrack } from '@/utils/track';

import Icon from '@/components/IconPro';

import HeaderDropdown from '../HeaderDropdown';
// import SelectLang from '../SelectLang';
import styles from './index.less';
// import getemployeemenu from '@/services/accessService';
// import { find } from '@/utils/utils';

@connect(({ global }) => ({
    global
}))
export default class GlobalHeaderRight extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            feedbackVisible: false
        };
    }

    getNoticeData() {
        const { notices = [] } = this.props;
        if (notices.length === 0) {
            return {};
        }
        const newNotices = notices.map(notice => {
            const newNotice = { ...notice };
            if (newNotice.datetime) {
                newNotice.datetime = moment(notice.datetime).fromNow();
            }
            if (newNotice.id) {
                newNotice.key = newNotice.id;
            }
            if (newNotice.extra && newNotice.status) {
                const color = {
                    todo: '',
                    processing: 'blue',
                    urgent: 'red',
                    doing: 'gold'
                }[newNotice.status];
                newNotice.extra = (
                    <Tag color={color} style={{ marginRight: 0 }}>
                        {newNotice.extra}
                    </Tag>
                );
            }
            return newNotice;
        });
        return groupBy(newNotices, 'type');
    }

    getUnreadData = noticeData => {
        const unreadMsg = {};
        Object.entries(noticeData).forEach(([key, value]) => {
            if (!unreadMsg[key]) {
                unreadMsg[key] = 0;
            }
            if (Array.isArray(value)) {
                unreadMsg[key] = value.filter(item => !item.read).length;
            }
        });
        return unreadMsg;
    };

    changeReadState = clickedItem => {
        const { id } = clickedItem;
        const { dispatch } = this.props;
        dispatch({
            type: 'global/changeNoticeReadState',
            payload: id
        });
    };

    fetchMoreNotices = tabProps => {
        const { list, name } = tabProps;
        const { dispatch, notices = [] } = this.props;
        const lastItemId = notices[notices.length - 1].id;
        dispatch({
            type: 'global/fetchMoreNotices',
            payload: {
                lastItemId,
                type: name,
                offset: list.length
            }
        });
    };

    render() {
        const {
            // fetchingMoreNotices,
            // fetchingNotices,
            // loadedAllNotices,
            // onNoticeVisibleChange,
            onMenuClick,
            // onNoticeClear,
            // skeletonCount,
            theme,
            // login,
            // companyId,
            currentUser,
            avatarFile: file
        } = this.props;
        // const currentUser = localStorage.getItem('user')
        //     ? JSON.parse(localStorage.getItem('user'))
        //     : {};
        // const storeCompanys = localStorage.getItem('companys');
        // const companys = storeCompanys ? JSON.parse(storeCompanys) : [];
        const menu = (
            <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
                {/* <Menu.Item key="userCenter">
                    <Icon type="user" />
                    <FormattedMessage
                        id="menu.account.center"
                        defaultMessage="account center"
                    />
                </Menu.Item>
                <Menu.Item key="userinfo">
                    <Icon type="setting" />
                    <FormattedMessage
                        id="menu.account.settings"
                        defaultMessage="account settings"
                    />
                </Menu.Item>
                <Menu.Item key="triggerError">
                    <Icon type="close-circle" />
                    <FormattedMessage
                        id="menu.account.trigger"
                        defaultMessage="Trigger Error"
                    />
                </Menu.Item> */}
                {currentUser && currentUser.isInit ? (
                    ''
                ) : (
                    <li key="usermessage" className={styles.menuUserBox}>
                        <Avatar
                            size="small"
                            className={styles.menuAvatar}
                            src={file && file.avatarFile && file.avatarFile.length > 0 ? file.avatarFile[0].url : ''}
                            alt=""
                        />
                        <span className={styles.menuUserName}>{currentUser.userName}</span>
                    </li>
                )}
                {currentUser && currentUser.isInit ? (
                    ''
                ) : (
                    <Menu.Item key="myInfo">
                        <IconUser />
                        <FormattedMessage id="menu.account.myInfo" defaultMessage="myInfo" />
                    </Menu.Item>
                )}
                {currentUser && currentUser.isInit ? (
                    ''
                ) : (
                    <Menu.Item key="passwordSettings">
                        <IconPassword />
                        <FormattedMessage id="menu.account.passwordSettings" defaultMessage="passwordSettings" />
                    </Menu.Item>
                )}
                {currentUser && currentUser.isInit ? (
                    ''
                ) : (
                    <Menu.Item
                        key="feedback"
                        onClick={() => {
                            eventTrack({
                                eventName: 'portal_personal_my_feedback_click',
                                pageName: 'portal'
                            });
                            this.setState({ feedbackVisible: true });
                        }}
                    >
                        <IconFeedback />
                        <FormattedMessage id="menu.account.feedback" defaultMessage="feedback" />
                    </Menu.Item>
                )}
                {currentUser && currentUser.isInit ? (
                    ''
                ) : (
                    <Menu.Item key="feedbackList">
                        <IconFeedbackList />
                        <FormattedMessage id="menu.account.feedbackList" defaultMessage="feedbackList" />
                    </Menu.Item>
                )}
                {currentUser && currentUser.isInit ? '' : <Menu.Divider style={{ margin: 0 }} />}
                <Menu.Item key="logout" style={{ paddingTop: 4, paddingBottom: 6 }}>
                    <FormattedMessage id="menu.account.logout" defaultMessage="logout" />
                </Menu.Item>
            </Menu>
        );
        // const loadMoreProps = {
        //     skeletonCount,
        //     loadedAll: loadedAllNotices,
        //     loading: fetchingMoreNotices
        // };
        // const noticeData = this.getNoticeData();
        // const unreadMsg = this.getUnreadData(noticeData);
        let className = styles.right;
        if (theme === 'dark') {
            className = `${styles.right}  ${styles.dark}`;
        }
        return (
            <>
                <FeedbackModal
                    visible={this.state.feedbackVisible}
                    onFinish={() => {
                        this.setState({ feedbackVisible: false });
                    }}
                    onCancel={() => {
                        this.setState({ feedbackVisible: false });
                    }}
                />
                <div
                    className={className}
                    onClick={() => {
                        eventTrack({
                            eventName: 'portal_personal_my_click',
                            pageName: 'personal_portal'
                        });
                    }}
                >
                    {/* <HeaderSearch
                    className={`${styles.action} ${styles.search}`}
                    placeholder={formatMessage({
                        id: 'component.globalHeader.search'
                    })}
                    dataSource={[
                        formatMessage({
                            id: 'component.globalHeader.search.example1'
                        }),
                        formatMessage({
                            id: 'component.globalHeader.search.example2'
                        }),
                        formatMessage({
                            id: 'component.globalHeader.search.example3'
                        })
                    ]}
                    onSearch={value => {
                        console.log('input', value); // eslint-disable-line
                    }}
                    onPressEnter={value => {
                        console.log('enter', value); // eslint-disable-line
                    }}
                />
                <NoticeIcon
                    className={styles.action}
                    count={currentUser.unreadCount}
                    onItemClick={(item, tabProps) => {
                        console.log(item, tabProps); // eslint-disable-line
                        this.changeReadState(item, tabProps);
                    }}
                    loading={fetchingNotices}
                    locale={{
                        emptyText: formatMessage({
                            id: 'component.noticeIcon.empty'
                        }),
                        clear: formatMessage({
                            id: 'component.noticeIcon.clear'
                        }),
                        viewMore: formatMessage({
                            id: 'component.noticeIcon.view-more'
                        }),
                        notification: formatMessage({
                            id: 'component.globalHeader.notification'
                        }),
                        message: formatMessage({
                            id: 'component.globalHeader.message'
                        }),
                        event: formatMessage({
                            id: 'component.globalHeader.event'
                        })
                    }}
                    onClear={onNoticeClear}
                    onPopupVisibleChange={onNoticeVisibleChange}
                    onViewMore={() => message.info('Click on view more')}
                    clearClose
                >
                    <NoticeIcon.Tab
                        count={unreadMsg.notification}
                        list={noticeData.notification}
                        title="notification"
                        emptyText={formatMessage({
                            id: 'component.globalHeader.notification.empty'
                        })}
                        emptyImage="https://gw.alipayobjects.com/zos/rmsportal/wAhyIChODzsoKIOBHcBk.svg"
                        showViewMore
                    />
                    <NoticeIcon.Tab
                        count={unreadMsg.message}
                        list={noticeData.message}
                        title="message"
                        emptyText={formatMessage({
                            id: 'component.globalHeader.message.empty'
                        })}
                        emptyImage="https://gw.alipayobjects.com/zos/rmsportal/sAuJeJzSKbUmHfBQRzmZ.svg"
                        showViewMore
                    />
                    <NoticeIcon.Tab
                        count={unreadMsg.event}
                        list={noticeData.event}
                        title="event"
                        emptyText={formatMessage({
                            id: 'component.globalHeader.event.empty'
                        })}
                        emptyImage="https://gw.alipayobjects.com/zos/rmsportal/HsIsxMZiWKrNUavQUXqx.svg"
                        showViewMore
                    />
                </NoticeIcon> */}

                    {/* 我的待办 */}
                    <div className={styles.selfTaskCountWrapper}>
                        <Tooltip placement="bottom" title="我的待办">
                            <Badge
                                count={
                                    (this.props.global?.userTask?.unFinishCount > 99
                                        ? '99+'
                                        : this.props.global?.userTask?.unFinishCount) || 0
                                }
                            >
                                <LinkTo to="/personal/todo">
                                    <Icon type="iconToDoLists" />
                                </LinkTo>
                            </Badge>
                        </Tooltip>
                    </div>

                    {currentUser.employeeCode ? (
                        <HeaderDropdown overlay={menu}>
                            <span className={`${styles.action} ${styles.account}`}>
                                <Avatar
                                    size="small"
                                    className={styles.avatar}
                                    src={
                                        file && file.avatarFile && file.avatarFile.length > 0
                                            ? file.avatarFile[0].url
                                            : ''
                                    }
                                    alt=""
                                />
                                <span className={styles.name}>{currentUser.userName}</span>
                            </span>
                        </HeaderDropdown>
                    ) : (
                        <Spin size="small" style={{ marginLeft: 8, marginRight: 8 }} />
                    )}
                    {/* <SelectLang className={styles.action} /> */}
                </div>
            </>
        );
    }
}
